package com.pirestupppai.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.pirestupppai.R;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.bean.LoginUser;
import com.pirestupppai.bean.TupaiUser;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.utils.WeakReferenceHandler;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;

/**
 * 重置密码
 *
 * @author: xiaoluo
 * @date: 2017-03-02 17:46
 */
public class ResetPasswdActivity extends BaseActivity{

    @BindView(R.id.input_phone_tv)
    EditText phoneEt;
    @BindView(R.id.input_passwd_et)
    EditText passwdEt;
    @BindView(R.id.verify_code)
    EditText codeEt;
    @BindView(R.id.get_verify_code)
    Button getCodeBtn;
    @BindView(R.id.sure_login_btn)
    Button sureLoginBtn;
    @BindView(R.id.back_image)
    ImageView backIv;

    private static final int RESEND_TIME_IN_SEC = 60; // 重新发送验证时间（秒）
    private static final int MSG_TIMER = 0x3312;
    private static final int MSG_CODE = 0x3333;

    private int mLeftTime = RESEND_TIME_IN_SEC;
    private WeakReferenceHandler mHandler = new WeakReferenceHandler(this);

    private String mPhoneNum;
    private String mPasswd;

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_reset_passwd;
    }

    @Override
    protected void initViews() {
        mPhoneNum = getIntent().getStringExtra(Constant.IntentKey.PHONE);
        phoneEt.setText(mPhoneNum);
        passwdEt.requestFocus();
    }

    @Override
    protected void initListeners() {
        getCodeBtn.setOnClickListener(this);
        backIv.setOnClickListener(this);
        sureLoginBtn.setOnClickListener(this);
    }

    @Override
    protected void initLogic() {
        codeReceiver();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_verify_code:
                getVerifyCode();
                break;
            case R.id.sure_login_btn:
                sureLoginBtn.setClickable(false);
                sureAndLogin();
                break;
            case R.id.back_image:
                finish();
                break;

        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_TIMER:
                // 重发倒计时
                if (mLeftTime > 1) {
                    mLeftTime--;
                    getCodeBtn.setEnabled(false);
                    getCodeBtn.setText(mLeftTime + "s后重发");
                    mHandler.sendEmptyMessageDelayed(MSG_TIMER, 1000);
                } else {
                    mLeftTime = RESEND_TIME_IN_SEC;
                    getCodeBtn.setEnabled(true);
                    getCodeBtn.setText("获取验证码");
                    getCodeBtn.setTextColor(Color.parseColor("#090909"));
                }
            case MSG_CODE:
                String codeMsg = msg.getData().getString("messagecode");
                if (codeMsg != null && codeMsg.length() >= 4 && codeMsg.length() <= 6) {
                    codeEt.setText(codeMsg);
                }
                Editable etext = passwdEt.getText();
                Selection.setSelection(etext, etext.length());
                break;

            default:
                break;

        }
        return true;
    }

    /**
     * 确定并登录
     */
    private void sureAndLogin() {
        mPasswd = passwdEt.getText().toString().trim();
        if (validate()) {
            NetworkRequest.getInstance().resetPasswd(mPhoneNum, codeEt.getText().toString(), mPasswd,
                    new TupaiSubscriber(mContext) {
                       @Override
                       protected void requestSuccess(Object o) {
                           Utils.showToast("重置密码成功");
                           login();
                       }

                       @Override
                       protected void requestError(String error) {
                           sureLoginBtn.setClickable(true);
                       }
                   });
        }
    }

    private void login() {
        NetworkRequest.getInstance().phoneLogin(mPhoneNum, mPasswd,
                new TupaiSubscriber<TupaiUser>(mContext) {
                    @Override
                    protected void requestSuccess(TupaiUser tupaiUser) {
                        sureLoginBtn.setClickable(true);
                        LoginUser.getInstance().initFromResponse(tupaiUser);

                        Intent intent = new Intent(mContext, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }

                    @Override
                    protected void requestError(String error) {
                        sureLoginBtn.setClickable(true);
                    }
                });
    }

    /**
         * 校验
         */
    private boolean validate() {
        if (TextUtils.isEmpty(mPasswd)) {
            Utils.showToast("请填写登录密码");
            passwdEt.requestFocus();
            sureLoginBtn.setClickable(true);
            return false;
        }

        if (passwdEt.length() < 6 || passwdEt.length() > 16) {
            Utils.showToast("密码6-16位字符");
            sureLoginBtn.setClickable(true);
            return false;
        }

        if (TextUtils.isEmpty(codeEt.getText().toString().trim())) {
            Utils.showToast("请填写验证码");
            codeEt.requestFocus();
            sureLoginBtn.setClickable(true);
            return false;
        }

        return true;
    }

    /**
     * 获取短信验证码
     */
    private void getVerifyCode() {
        mLeftTime = 60;
        mLeftTime--;
        getCodeBtn.setEnabled(false);
        getCodeBtn.setText(mLeftTime + "s后重发");
        getCodeBtn.setTextColor(Color.parseColor("#66090909"));
        mHandler.sendEmptyMessageDelayed(MSG_TIMER, 1000);

        NetworkRequest.getInstance().getVerifyCode(mPhoneNum, new TupaiSubscriber(mContext) {
            @Override
            protected void requestSuccess(Object o) {

            }

            @Override
            protected void requestError(String error) {

            }
        });
    }

    /**
     * BroadcastReceiver拦截短信验证码
     */
    private void codeReceiver() {
        IntentFilter filter = new IntentFilter();
        //设置短信拦截参数
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter.setPriority(Integer.MAX_VALUE);
        BroadcastReceiver smsReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Object[] objs = (Object[]) intent.getExtras().get("pdus");
                for (Object obj : objs) {
                    byte[] pdu = (byte[]) obj;
                    SmsMessage sms = SmsMessage.createFromPdu(pdu);
                    String message = sms.getMessageBody();
                    String from = sms.getOriginatingAddress();
                    if (!TextUtils.isEmpty(from)) {
                        String code = patternCode(message);
                        if (!TextUtils.isEmpty(code)) {
                            Message msg = mHandler.obtainMessage();
                            msg.what = MSG_CODE;
                            Bundle bundle = new Bundle();
                            bundle.putString("messagecode", code);
                            msg.setData(bundle);
                            mHandler.sendMessage(msg);
                        }
                    }
                }
            }
        };
        registerReceiver(smsReceiver, filter);
    }

    /**
     * 匹配验证码
     */
    private String patternCode(String patternContent) {
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }
        String patternCoder = "(?<!\\d)\\d{4}(?!\\d)";
        Pattern p = Pattern.compile(patternCoder);
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

}
